package org.edu.controller;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.struts2.ServletActionContext;
import org.edu.bean.User;
import org.edu.dao.PublicDao;
import com.opensymphony.xwork2.ActionSupport;

public class FilesController extends ActionSupport {
	@Resource PublicDao publicDao;
	private File file;
	private String fileName;
	private String fileURL;
	private String tbname;

	public String srcdownload() {
		Long time = new Date().getTime();
		String rp = ServletActionContext.getServletContext().getRealPath(
				"\\excel");
		setFileName(time.toString() + ".xls");
		String name = rp + "\\" + time + ".xls";
		setFileURL("\\excel\\" + time + ".xls");
		String Hsql="from "+tbname;
		
		List ls=publicDao.findListByHSql(Hsql);
		try
		{
			WritableWorkbook book = Workbook.createWorkbook(new File(name));
			WritableSheet sheet = book.createSheet("Sheet_1",0);
			 
			Label label = null;
			PropertyDescriptor[] props = null;
			 
			for (int i = 0;i < ls.size();i++)
			{
				props = Introspector.getBeanInfo(ls.get(i).getClass(), Object.class)
	                    .getPropertyDescriptors();
				for (int j = 0;j < props.length;j++)
				{
					if(0==i){
						Label lb = new Label(j,0,props[j].getName().toString() );
						sheet.addCell(lb);
					}
					label = new Label(j,i+1,props[j].getReadMethod().invoke(ls.get(i)).toString()  );
					sheet.setColumnView(j,20);
					sheet.addCell(label);
				}
			}
			book.write();
			book.close();

		} catch(Exception e)
		{
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public InputStream getInputStream() throws Exception {
		InputStream in = ServletActionContext.getServletContext()
				.getResourceAsStream(getFileURL());
		return in;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFileURL() {
		return fileURL;
	}

	public void setFileURL(String fileURL) {
		this.fileURL = fileURL;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getTbname() {
		return tbname;
	}

	public void setTbname(String tbname) {
		this.tbname = tbname;
	}

}
